﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
using Lon.IO.Station;
using Lon.Data.Station;


namespace Lon.UI.Station
{
    public partial class FormAnalogView : FormTableWithTree
    {
        string dbm;
       
        AnalogConfigGroup configGroup = null;
        Thread displayThread = null;
        const int realValColumn = 2;
        const int realValOccurTimeColumn= 3;
        public FormAnalogView()
            : this(LonConfigManager.CurrDbm)
        {

        }
        public FormAnalogView(string dbm)
        {
            this.dbm = dbm;
            InitializeComponent();
        }

        private void FormAnalogView_Load(object sender, EventArgs e)
        {
            InitSelectTree();
            this.dgvTable.ColumnCount = 8;
            dgvTable.Columns[0].HeaderText = "序号";
            dgvTable.Columns[1].HeaderText = "名称";
            dgvTable.Columns[2].HeaderText = "实际值";
            dgvTable.Columns[3].HeaderText = "数据更新时间";
            dgvTable.Columns[4].HeaderText = "最大值\r\n(查看时间内)";
            dgvTable.Columns[5].HeaderText = "数据更新时间";
            dgvTable.Columns[6].HeaderText = "最大值\r\n(查看时间内)";
            dgvTable.Columns[7].HeaderText = "数据更新时间";
           
            dgvTable.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dgvTable.Columns[5].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dgvTable.Columns[7].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

            if (treeTableSelect.Nodes.Count < 1) return;
            this.dbm = treeTableSelect.Nodes[0].Text;
            if (treeTableSelect.Nodes[0].Nodes.Count < 1) return;
            TreeNode node = treeTableSelect.Nodes[0].Nodes[0];
            if (node == null) return;
            object obj = node.Tag;
            if (obj is AnalogConfigGroup)
            {
                this.configGroup = (AnalogConfigGroup)obj;
                ShowTable();
            }
        }

        void ClearTable()
        {
            this.dgvTable.RowCount = 1;
        }

        private void ShowTable()
        {
            if (configGroup == null) return;
            this.Text = configGroup.Name + "实时查看--" + dbm;
            ClearTable();


            int propertyCount = configGroup.GetCount();
            for (int i = 0; i < propertyCount; i++)
            {
                AnalogProperty property = configGroup.GetProperty(i);
                float occurUpLimit = 0;
                float upperLimit = 0;
 
                if (property.AlarmUpperLimit != null && property.AlarmUpperLimit.Length > 1)
                    occurUpLimit = property.AlarmUpperLimit[0];
                if (property.AlarmUpperLimit != null && property.AlarmUpperLimit.Length > 2)
                    upperLimit = property.AlarmUpperLimit[1];
                if (property.AlarmUpperLimit != null && property.AlarmLowerLimit.Length > 2)
                    upperLimit = property.AlarmLowerLimit[1];
                DateTime nowTime = DateTime.Now;

                Object[] row = new Object[] {
                    i,
                    
                    property.Name,
                    "未知",
                    nowTime,
                    "未知",
                    nowTime,
                     "未知",
                    nowTime
                  
                };

                dgvTable.Rows.Add(row);

                dgvTable.Rows[dgvTable.Rows.Count - 1].Tag = property;
            }
            if (displayThread != null && displayThread.IsAlive)
            {
                displayThread.Abort();
            }
            displayThread = new Thread(new ThreadStart(DisplayProc));
            displayThread.IsBackground = true;
            displayThread.Start();
        }

        private void DisplayProc()
        {
            AnalogDisplayPort port = new AnalogDisplayPort();
            try
            {
                
                port.Open();
                port.ClrBuffer();
                while (true)
                {
                    StationFrame frame = null;
                    if (port.Read(ref frame))
                    {
                        if (frame == null) continue;
                        if (frame.Dbm != dbm) continue;
                        if (frame.FrameType != StationFrameType.Analog) continue;
                        if (frame.TypeId != configGroup.GetSubType()) continue;
                        if (frame.Index < 0) continue;
                        DisplayFrame(frame as StationAnalogFrame);
                        
                    }
                }
            }
            catch
            {
                Trace.WriteLine("Info:显示线程退出");
            }
            port.Close();
        }

        private delegate void DelegateDgvDisplay(StationAnalogFrame frame);

       


        private void DisplayFrame(StationAnalogFrame frame)
        {
            if (InvokeRequired)
            {
                this.Invoke(new DelegateDgvDisplay(DisplayFrame), new object[] { frame });
            }
            else
            {
                if (frame.Index >= dgvTable.Rows.Count) return;
                dgvTable.Rows[frame.Index].Cells[realValColumn].Value = frame.Val.Val;
                dgvTable.Rows[frame.Index].Cells[realValOccurTimeColumn].Value = frame.Val.OccurTime;
            }
        }

        private void InitSelectTree()
        {
            foreach (StationCfg stationCfg in LonConfigManager.stationDict.Values)
            {
                TreeNode stationNode = new TreeNode(stationCfg.Dbm);
                stationNode.Tag = stationCfg;
                treeTableSelect.Nodes.Add(stationNode);
              
                List<AnalogConfigGroup> analogGroupList
                    = stationCfg.AnalogConfigGroupManager.GetGroupList();
                foreach (AnalogConfigGroup group in analogGroupList)
                {
                    TreeNode groupNode = new TreeNode(group.Name);
                    groupNode.Tag = group;
                    stationNode.Nodes.Add(groupNode);
                }
            }
            treeTableSelect.MouseClick += new MouseEventHandler(treeTableSelect_MouseClick);

            

            
        }

        void treeTableSelect_MouseClick(object sender, MouseEventArgs e)
        {
            TreeNode node = treeTableSelect.GetNodeAt(e.Location);
            if (node == null) return;
            object obj = node.Tag;
            if (obj is AnalogConfigGroup)
            {
                if (node.Parent == null) return;
                string newDbm = node.Parent.Text;
                if (String.IsNullOrEmpty(newDbm)) return;
                if (newDbm != dbm)
                {
                    dbm = newDbm;

                }
                this.configGroup = (AnalogConfigGroup)obj;
                ShowTable();
            }
            else
            {

                //node.Expand();


            }
        }

        private void FormAnalogView_Shown(object sender, EventArgs e)
        {
           
        }

        private void FormAnalogView_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason != CloseReason.MdiFormClosing)
            {
                e.Cancel = true;
                this.Hide();
                if (displayThread != null && displayThread.IsAlive)
                {
                    displayThread.Abort();
                }
            }
        }

        private void FormAnalogView_VisibleChanged(object sender, EventArgs e)
        {
            if (this.IsHidden == false) ShowTable();  
                
           
        }

    }
}
